package tcptest;

import org.junit.Test;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * @author 李泽伟
 */
public class MainTest {
    /**
     * 客户端
     */
    @Test
    public void client(){
        OutputStream os = null;
        Socket socket = null;
        try {
            //1.创建Socket对象，指明服务器ip和端口号
            InetAddress localhost = InetAddress.getByName("localhost");
            socket = new Socket(localhost, 8899);
            //2.获取一个输出流，用于输出数据
            os = socket.getOutputStream();
            //3.客户端写出数据
            os.write("hello world".getBytes());
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            //4.资源的关闭
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 服务器
     */
    @Test
    public void serverTest() {
        ByteArrayOutputStream buffer = null;
        ServerSocket ss = null;
        InputStream stream = null;
        try {
            //1.创建服务器端的ServerSocket，指明自己的端口号
            ss = new ServerSocket(8899);
            //2.接收来自客户端的socket
            Socket socket = ss.accept();
            //3.获取输入流
            stream = socket.getInputStream();
            //建议使用ByteArrayOutputStream防止乱码
            //4.接收输入流的数据
            buffer = new ByteArrayOutputStream();
            byte[] buf = new byte[10];
            int len;
            while((len = stream.read(buf))!=-1){
                buffer.write(buf, 0, len);
            }
            String str = buffer.toString();
            System.out.println(str);
            System.out.println("收到了来自：" + socket.getInetAddress().getHostName()+"的数据");
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            //5.资源的关闭
            try {
                if (ss != null) {
                    ss.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (stream != null) {
                    stream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (buffer != null) {
                    buffer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
